package com.zijin.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            // 1. 加载主配置文件
            String resource = "Configuration.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);

            // 2. 构建SqlSessionFactory
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            // 3. 关闭资源
            inputStream.close();
        } catch (IOException e) {
            throw new RuntimeException("初始化MyBatis失败", e);
        }
    }

    // 获取SqlSession（自动提交事务）
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession(true);
    }

    // 获取SqlSession（手动控制事务）
    public static SqlSession getSqlSession(boolean autoCommit) {
        return sqlSessionFactory.openSession(autoCommit);
    }

    // 关闭SqlSession
    public static void closeSqlSession(SqlSession sqlSession) {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }
}